package com.tiger.userClient.http.message;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tiger.db.entity.App;
import com.tiger.userClient.Db;
import com.tiger.userClient.caspOpeapi.Openapi;
import com.tiger.userClient.http.message.dto.ListDto;
import com.tiger.utils.ResponseUtil;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/message")
public class MessageController {
    private final Db db;
    private final Openapi openapi;

    public MessageController(Db db, Openapi openapi) {
        this.db = db;
        this.openapi = openapi;
    }

    @PostMapping("list")
    public Object list(@RequestBody ListDto dto, @RequestAttribute("userKey") String userKey) {
        System.out.println("msg list userKey");
        System.out.println(userKey);
        List<HashMap> list = openapi.messageList(userKey, dto.getAppId());

        List<HashMap<String, Object>> rows = new ArrayList<>();

        if(list != null && !list.isEmpty()) {
            List<String> appIds = new ArrayList<>();
            HashMap<String, List<HashMap>> appIdToMsgList = new HashMap<>();

            for(HashMap item : list) {
                String appId = (String) item.get("appId");
                if(appId != null && !appId.isEmpty()) {
                    if(!appIds.contains(appId)) {
                        appIds.add(appId);
                    }


                    if(!appIdToMsgList.containsKey(appId)) {
                        appIdToMsgList.put(appId, new ArrayList<>());
                    }
                    appIdToMsgList.get(appId).add(item);
                }
            }

            if(appIds.isEmpty()) return ResponseUtil.successRes(rows);

            List<App> apps = db.app.list(new LambdaQueryWrapper<App>().select(App::getId, App::getSourceKey, App::getName, App::getCover).in(App::getSourceKey, appIds));
            if(!apps.isEmpty()) {
                for(App app : apps) {
                    List<HashMap> msgList = appIdToMsgList.get(app.getSourceKey());
                    if(msgList != null) {
                        HashMap<String, Object> row = new HashMap<>();
                        row.put("appId", app.getSourceKey());
                        row.put("name", app.getName());
                        row.put("cover", app.getCover());
                        row.put("msgList", msgList);

                        rows.add(row);
                    }
                }

            }
        }


        return ResponseUtil.successRes(rows);
    }

    @GetMapping("count")
    public Object count(@RequestAttribute("userKey") String userKey) {
        int count = openapi.unReadmessageCount(userKey);
        return ResponseUtil.successRes(count);
    }
}
